#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define NUM 1024

class Tcpclient
{
public:
    Tcpclient(const std::string serverip, const uint16_t serverport) : _serverip(serverip), _serverport(serverport), _sock(-1)
    {
    }
    void initClient()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            std::cerr << "socket create error" << std::endl;
            exit(2);
        }

    }
    void start()
    {  struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverport);
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());
        if(connect(_sock,(struct sockaddr*)&server,sizeof(server))!=0)
        {
            std::cerr << "socket connect error" << std::endl;
        }
        else
        { std::string s;
            while(true)
            {  //1.发信息
                std::cout<<"enter";
                std::getline(std::cin,s);
                write(_sock,s.c_str(),s.size());
                //2.收信息
                char buffer[NUM];
                int n=read(_sock,buffer,sizeof(buffer)-1);
                if(n > 0)
                {
                    //目前我们把读到的数据当成字符串, 截止目前
                    buffer[n] = 0;
                    std::cout << "Server回显# " << buffer << std::endl;
                }
                else
                {
                    break;
                }
            }
            
        }
         
    }
    ~Tcpclient()
    {
        if(_sock >= 0) close(_sock);
    }

private:
    uint16_t _serverport;
    std::string _serverip;
    int _sock;
};